/*
 * @Author: taiyunhang
 * @Date: 2019-02-22 15:16:34
 * */
const projectName = 'ShengDaZhonglv';
class LocalStorage {
  constructor() {}
  setLocalStorage(key, value, time) {
    let _key = projectName + "_" + key;
    localStorage.removeItem(_key);
    let isObject = value instanceof Object,
      _time = new Date().getTime(),
      _age = time;

    // 如果不是对象，新建一个对象把 value 存起来
    if (!isObject) {
      var b = value;
      value = {};
      value._value = b;
    }
    // 加入时间
    value._time = _time;
    // 过期时间
    value._age = _time + _age;
    // 是否一个对象
    value._isObject = isObject;
    localStorage.setItem(_key, JSON.stringify(value));
    return this;
  }
  isTimeout(key) {
    let isExpire = false,
      value = localStorage.getItem(key),
      now = new Date().getTime();
    if (value) {
      value = JSON.parse(value);
      // 当前时间是否大于过期时间
      isExpire = now > value._age;
    } else {
      isExpire = true
      // 没有值也是过期
    }
    return isExpire;
  }
  getLocalStorage(key) {
    let _key = projectName + "_" + key;
    let isExpire = this.isTimeout(_key);
    let  value = localStorage.getItem(_key);
    if (isExpire) {
      value = this.delLocalStorage(key);
    }else{
      value = JSON.parse(value);
      value = value._value;
    }
    return value;
  }
  delLocalStorage(key) {
    let _key = projectName + "_" + key;
    localStorage.removeItem(key);
  }
}

export default new LocalStorage();
